package cn.com.cifi.mars.util;


import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtUtil {

    /** token秘钥，请勿泄露，请勿随便修改 */
    public static final String SECRET = "mars3.1415926";
    public static final int calendarField = Calendar.HOUR;
    public static final int calendarInterval = 2;

    /**
     * JWT生成Token.<br/>
     * JWT构成: header, payload, signature
     * @param uid
     * 登录成功后用户uid, 参数uid不可传空
     */
    public static String createToken(String uid)  {
    	
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "mars") // payload
                .withClaim("aud", "mars")
                .withClaim("uid", null == uid ? null : uid.toString())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature
        return token;
    }

    /**
     * 解密Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT	jwt = verifier.verify(token);            
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     * @param token
     * @return user_id
     */
    public static String getUID(String token) {
    	String uid = null;
        Map<String, Claim> claims = verifyToken(token);
        Claim uid_claim = claims.get("uid");
        
        if (null == uid_claim || StringUtils.isEmpty(uid_claim.asString())) {
            // token 校验失败, 抛出Token验证非法异常
        }else {
        	uid = uid_claim.asString();
        }
        return uid;
    } 
    
    public static void main(String[] args) {
    	String uid = getUID("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJtYXJzIiwidWlkIjoiNjAwMDAwMyIsImlzcyI6Im1hcnMiLCJleHAiOjE1NjgyMTg0NzMsImlhdCI6MTU2ODIxMTI3M30.XJfrpI5bc1D6UB9Ye_SY9ZAf12OlS9K2QghXN0wEaW0");
//    	log.info(uid);
    	
//    	log.info(createToken("6000003"));
	}
   
}

